package cn.edu.nwafu.core.service.impl;

import cn.edu.nwafu.common.exception.Assert;
import cn.edu.nwafu.common.result.ResponseEnum;
import cn.edu.nwafu.core.mapper.UserInfoMapper;
import cn.edu.nwafu.core.pojo.entity.UserInfo;
import cn.edu.nwafu.core.pojo.query.UserInfoQuery;
import cn.edu.nwafu.core.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhanghao
 * @since 2021-10-30
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Override
    public IPage<UserInfo> listPage(Page<UserInfo> pageParam, UserInfoQuery userInfoQuery) {

        if (userInfoQuery == null) {
            return baseMapper.selectPage(pageParam, null);
        }
        String name = userInfoQuery.getName();
        String idCard = userInfoQuery.getIdCard();
        Integer passengerType = userInfoQuery.getPassengerType();

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper
                .eq(StringUtils.isNotBlank(name), "name", name)
                .eq(StringUtils.isNotBlank(idCard), "id_card", idCard)
                .eq(passengerType != null, "passenger_type", passengerType);

        return baseMapper.selectPage(pageParam, userInfoQueryWrapper);
    }

    @Override
    public void saveUser(UserInfo userInfo) {

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("id_card", userInfo.getIdCard());

        Integer count = baseMapper.selectCount(userInfoQueryWrapper);
        Assert.isTrue(count == 0, ResponseEnum.USER_EXIST_ERROR);

        baseMapper.insert(userInfo);
    }
}
